package com.itboye.bylibrary.widget;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.support.annotation.NonNull;

import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;
import com.itboye.bylibrary.util.ScreenUtil;

import java.security.MessageDigest;

public class GlideRatioTransform extends BitmapTransformation {


    private static float radius = 0f;
    Context context;

    public GlideRatioTransform(Context context) {
        this(context, 4);
    }

    public GlideRatioTransform(Context context, int dp) {
        this.radius = Resources.getSystem().getDisplayMetrics().density * dp;
        this.context = context;
    }

    @Override
    protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
        return roundCrop(pool, toTransform);
    }

    private Bitmap roundCrop(BitmapPool pool, Bitmap source) {
        if (source == null) return null;
        int imageWidth = source.getWidth();
        int imageHeight = source.getHeight();
        int width = ScreenUtil.getScreenWidth(context);//固定宽度
        int height = width * imageHeight / imageWidth;
        Bitmap result = pool.get(width, height, Bitmap.Config.ARGB_8888);
        if (result == null) {
            result = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
        }


//        //宽度固定,然后根据原始宽高比得到此固定宽度需要的高度
//        ViewGroup.LayoutParams para = imageView.getLayoutParams();
//        para.height = height;
//        para.width = width;
//        imageView.setImageBitmap(resource);
        Canvas canvas = new Canvas(result);
        Paint paint = new Paint();
        paint.setShader(new BitmapShader(source, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
        paint.setAntiAlias(true);
        RectF rectF = new RectF(0f, 0f, source.getWidth(), source.getHeight());
        canvas.drawRoundRect(rectF, radius, radius, paint);
        return result;
    }

    /**
     * Adds all uniquely identifying information to the given digest.
     * <p>
     * <p> Note - Using {@link MessageDigest#reset()} inside of this method will result
     * in undefined behavior. </p>
     *
     * @param messageDigest
     */
    @Override
    public void updateDiskCacheKey(@NonNull MessageDigest messageDigest) {

    }
//
//    @Override public String getId() {
//        return getClass().getName() + Math.round(radius);
//    }

}
